package com.astrob.TileSource;

import org.osmdroid.tileprovider.MapTile;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;

/**
 * Created by colin on 2017/10/10.
 *

 <provider id="6014" type="5" visible="true" background="-1">
 <name>卫星图</name>
 <mode>微软卫星</mode>
 <countries>China</countries>
 <url><![CDATA[http://t1.tiles.ditu.live.com/tiles/h{c}.png?g=3045&mkt=zh-cn]]></url>
 <zoomPart>{z}-8</zoomPart>
 <zoomMin>8</zoomMin>
 <zoomMax>25</zoomMax>
 <tileSize>256</tileSize>
 <attribution><![CDATA[微软卫星 Locus群3035043]]></attribution>
 <extraHeader><![CDATA[Referer#http://dev.ditu.bing.com/]]></extraHeader>
 <extraHeader><![CDATA[User-Agent#Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0]]></extraHeader>
 </provider>
 */

public class MicrosoftMapsTileSource extends OnlineTileSourceBase {
    /**
     * @param aName                a human-friendly name for this tile source  自定图源义名字，会在手机外部存储中新建以该名字命名的文件夹，瓦片存储在其中
     * @param aZoomMinLevel        the minimum zoom level this tile source can provide  最小缩放级别
     * @param aZoomMaxLevel        the maximum zoom level this tile source can provide  最大缩放级别
     * @param aTileSizePixels      the tile size in pixels this tile source provides  瓦片质量 （256）
     * @param aImageFilenameEnding the file name extension used when constructing the filename  瓦片格式（jpg[有损压缩率高、不透明]、png[无损、透明]）
     * @param aBaseUrl             the base url(s) of the tile server used when constructing the url to download the tiles  下载瓦片的链接（前缀）
     */
    public MicrosoftMapsTileSource(String aName, int aZoomMinLevel, int aZoomMaxLevel, int aTileSizePixels,
                                   String aImageFilenameEnding, String[] aBaseUrl) {
        super(aName, aZoomMinLevel, aZoomMaxLevel, aTileSizePixels, aImageFilenameEnding, aBaseUrl);
    }


    @Override
    public String getTileURLString(final MapTile aTile) {
        return getBaseUrl() + "h" + quadTree(aTile) + ".png?g=3045&mkt=zh-cn";
    }

    /**
     * Converts TMS tile coordinates to QuadTree
     *
     * @param aTile
     *            The tile coordinates to convert
     * @return The QuadTree as String.
     */
    protected String quadTree(final MapTile aTile) {
        final StringBuilder quadKey = new StringBuilder();
        for (int i = aTile.getZoomLevel(); i > 0; i--) {
            int digit = 0;
            final int mask = 1 << (i - 1);
            if ((aTile.getX() & mask) != 0)
                digit += 1;
            if ((aTile.getY() & mask) != 0)
                digit += 2;
            quadKey.append("" + digit);
        }

        return quadKey.toString();
    }
}